package com.csot.ry.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.NumberUtil;
import com.csot.ry.domain.TDcnCity;
import com.jfinal.plugin.activerecord.Record;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.csot.config.Caches;
import com.csot.model.CitySegment;
import com.csot.ry.domain.TCheckSegment;
import com.csot.ry.domain.TCitySegment;
import com.csot.ry.mapper.TCityIpMapper;
import com.csot.ry.mapper.TCitySegmentMapper;
import com.csot.ry.service.ITCitySegmentService;
import com.csot.ry.util.CacheKitUtil;
import com.csot.ry.util.UserUtils;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;
import com.csot.common.core.domain.entity.SysRole;
import com.csot.common.core.domain.entity.SysUser;
import com.csot.common.core.text.Convert;
import com.csot.common.exception.ServiceException;
import com.csot.common.utils.DateUtils;
import com.csot.common.utils.SecurityUtils;
import com.csot.common.utils.StringUtils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.BiMap;
import cn.hutool.core.net.Ipv4Util;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 城市ip段Service业务层处理
 *
 * @author 刘沙
 * @date 2022-05-31
 */
@Service
public class TCitySegmentServiceImpl implements ITCitySegmentService {
    private static final Logger log = LoggerFactory.getLogger(TCitySegmentServiceImpl.class);
    private CitySegment csdao = new CitySegment().dao();
    @Autowired
    private TCitySegmentMapper tCitySegmentMapper;

    @Autowired
    private TCityIpMapper tCityIpMapper;

    private BiMap<String, String> ip_type = CacheKit.get("dict-data", "ip_type");
    private BiMap<String, String> ip_city = CacheKit.get("dict-data", "ip_city");
    private BiMap<String, String> ip_use_type = CacheKit.get("dict-data", "ip_use_type");
    private BiMap<String, String> ip_status = CacheKit.get("dict-data", "ip_status");

    /**
     * 查询城市ip段
     *
     * @param id 城市ip段主键
     * @return 城市ip段
     */
    @Override
    public TCitySegment selectTCitySegmentById(Long id) {
        return tCitySegmentMapper.selectTCitySegmentById(id);
    }

    /**
     * 查询城市ip段列表
     *
     * @param tCitySegment 城市ip段
     * @return 城市ip段
     */
    @Override
    public List<TCitySegment> selectTCitySegmentList(TCitySegment tCitySegment) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        List<String> roleKeys = roles.stream().map(r -> {
            return "'" + r.getRoleKey() + "'";
        }).collect(Collectors.toList());
        String iptype = StringUtils.join(roleKeys, ",");
        if (iptype.indexOf("admin") > -1) {
            if (StrUtil.isNotEmpty(tCitySegment.getIpType())) {
                tCitySegment.setIpType("'" + tCitySegment.getIpType() + "'");
            }
        } else if (StrUtil.isNotEmpty(tCitySegment.getIpType())) {
            if (iptype.indexOf(tCitySegment.getIpType()) < 0) {
                throw new IllegalArgumentException("没有此网络类型的权限！");
            } else {
                tCitySegment.setIpType("'" + tCitySegment.getIpType() + "'");
            }
        } else {
            tCitySegment.setIpType(iptype);
        }
        Long deptid = user.getDeptId();
        if (iptype.indexOf("admin") > -1) {

        } else if (deptid != 100) {
            tCitySegment.setIpCity(CacheKitUtil.ip_dept.get(user.getDept().getParentId() + ""));
        }

        try {
            if (StrUtil.isNotEmpty(tCitySegment.getIpStart())) {
                tCitySegment.setIpStartI(NetUtil.ipv4ToLong(tCitySegment.getIpStart().trim()));
            }
            if (StrUtil.isNotEmpty(tCitySegment.getIpEnd())) {
                tCitySegment.setIpEndI(NetUtil.ipv4ToLong(tCitySegment.getIpEnd().trim()));
            }
        } catch (Exception e) {
            log.error("", e);
            throw new IllegalArgumentException("起止IP不正确");
        }
        return tCitySegmentMapper.selectTCitySegmentList(tCitySegment);
    }

    /**
     * 查询城市ip段列表
     *
     * @param tCitySegments 城市ip段列表
     * @return 城市ip段
     */
    @Override
    public List<TCitySegment> selectTCitySegmentLists(List<TCitySegment> tCitySegments) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<SysRole> roles = user.getRoles();
        List<String> roleKeys = roles.stream().map(r -> {
            return "'" + r.getRoleKey() + "'";
        }).collect(Collectors.toList());
        String iptype = StringUtils.join(roleKeys, ",");

        Long deptid = user.getDeptId();
        Long pdeptid = deptid;
        if (deptid != 100) {
            pdeptid = user.getDept().getParentId();
        }
        //如果取不到上级部门，并且有管理员权限，设置为全省
        if (null == deptid && iptype.contains("admin")) {
            pdeptid = 100L;
        }
        String city_e = CacheKitUtil.ip_dept.get(String.valueOf(pdeptid));

        List<TCitySegment> returnList = ListUtil.toCopyOnWriteArrayList(new ArrayList<>());
        for (TCitySegment tCitySegment : tCitySegments) {
            try {
                if (deptid != 100) {
                    tCitySegment.setIpCity(city_e);
                }
                if (StrUtil.isNotEmpty(tCitySegment.getIpStart())) {
                    tCitySegment.setIpStartI(NetUtil.ipv4ToLong(tCitySegment.getIpStart().trim()));
                }
                if (StrUtil.isNotEmpty(tCitySegment.getIpEnd())) {
                    tCitySegment.setIpEndI(NetUtil.ipv4ToLong(tCitySegment.getIpEnd().trim()));
                }
                if (StrUtil.isNotEmpty(tCitySegment.getIpCity())
                        && StrUtil.isNotEmpty(ip_city.getKey(tCitySegment.getIpCity()))) {
                    tCitySegment.setIpCity(ip_city.getKey(tCitySegment.getIpCity()));
                }
                if (StrUtil.isNotEmpty(tCitySegment.getIpStatus())
                        && StrUtil.isNotEmpty(ip_status.getKey(tCitySegment.getIpStatus()))) {
                    tCitySegment.setIpStatus(ip_status.getKey(tCitySegment.getIpStatus()));
                }
                if (StrUtil.isNotEmpty(tCitySegment.getIpUseType())
                        && StrUtil.isNotEmpty(ip_use_type.getKey(tCitySegment.getIpUseType()))) {
                    tCitySegment.setIpUseType(ip_use_type.getKey(tCitySegment.getIpUseType()));
                }

            } catch (Exception e) {
                throw new ServiceException("起止IP不正确");
            }
        }

        tCitySegments.parallelStream().forEach(tCitySegment -> {
            List<TCitySegment> csList = tCitySegmentMapper.selectTCitySegmentList(tCitySegment);
            if (CollUtil.isNotEmpty(csList)) {
                returnList.addAll(csList);
            }
        });

        return returnList;
    }

    /**
     * 新增城市ip段
     *
     * @param tCitySegment 城市ip段
     * @return 结果
     */
    @Override
    public int insertTCitySegment(TCitySegment tCitySegment) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (!"admin".equals(user.getUserName())) {
//            if (!UserUtils.isRole(tCitySegment.getIpType())) {
//                throw new ServiceException("创建失败！您没有该网络类型权限");
//            }
            if (StrUtil.isBlank(tCitySegment.getIpType())) {
                tCitySegment.setIpType("ip_area");
            }
            Long deptid = user.getDeptId();
            String pdeptname = CacheKitUtil.ip_dept.get(String.valueOf(user.getDept().getParentId()));
            if (deptid != 100 && StrUtil.isNotEmpty(tCitySegment.getIpCity())
                    && !tCitySegment.getIpCity().equals(pdeptname)) {
                throw new ServiceException("不能创建其他地市的信息");
            }
        }

        tCitySegment.setCreateTime(DateUtils.getNowDate());
        tCitySegment.setIpStartI(NetUtil.ipv4ToLong(tCitySegment.getIpStart().trim()));
        tCitySegment.setIpEndI(NetUtil.ipv4ToLong(tCitySegment.getIpEnd().trim()));
        if (tCitySegment.getIpEndI() < tCitySegment.getIpStartI()) {
            throw new IllegalArgumentException("起始地址不能大于终止地址。");
        }

        List<?> repeatList = Db.find(
                "select distinct id from t_total_segment where ip_start_i <= ? and ip_end_i >= ? and ip_type = ? ",
                tCitySegment.getIpStartI(), tCitySegment.getIpEndI(), tCitySegment.getIpType());
        if (repeatList.size() != 1) {
            throw new ServiceException(String.format("数据异常: %s", "起始地址和终止地址在省地址中未分配"));
        }

        int result = tCitySegmentMapper.selectTCitySegmentIfExist(tCitySegment);
        if (result > 0) {
            throw new ServiceException("插入失败：此地址范围已存在");
        }

        return tCitySegmentMapper.insertTCitySegment(tCitySegment);
    }

    /**
     * 修改城市ip段
     *
     * @param tCitySegment 城市ip段
     * @return 结果
     */
    @Override
    @Transactional
    public int updateTCitySegment(TCitySegment tCitySegment) {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long deptid = user.getDeptId();
        String pdeptname = CacheKitUtil.ip_dept.get(user.getDept().getParentId() + "");
        if (!"admin".equals(user.getUserName())) {
            if (deptid != 100 && StrUtil.isNotEmpty(tCitySegment.getIpCity())
                    && !tCitySegment.getIpCity().equals(pdeptname)) {
                throw new ServiceException("不能修改其他地市的信息");
            }
        }

        TCitySegment tCitySegmentOld = this.selectTCitySegmentById(tCitySegment.getId());
        // 修改只能在原段内进行
        long newIpStartI = NetUtil.ipv4ToLong(tCitySegment.getIpStart().trim());
        long newIpEndI = NetUtil.ipv4ToLong(tCitySegment.getIpEnd().trim());
        tCitySegment.setIpEndI(newIpStartI);
        tCitySegment.setIpStartI(newIpStartI);
        if (newIpEndI < newIpStartI) {
            throw new ServiceException("终止IP不能小于起始IP！");
        }
        // 1、验证是否可以更新
        if (tCitySegmentOld.getIpStartI() > newIpStartI || tCitySegmentOld.getIpEndI() < newIpEndI) {
            throw new ServiceException("始止IP不能在原IP段之外！");
        }

        if (tCitySegmentOld.getIpEndI().compareTo(tCitySegment.getIpEndI()) == 0
                && tCitySegmentOld.getIpStartI().compareTo(tCitySegment.getIpStartI()) == 0
                && tCitySegmentOld.getIpType().equals(tCitySegment.getIpType())
                && tCitySegmentOld.getIpCity().equals(tCitySegment.getIpCity())) {
            return tCitySegmentMapper.updateTCitySegment(tCitySegment);
        }

        tCityIpMapper.deleteTCityIpBySegmentId(tCitySegment.getId());
        int delcount = this.deleteTCitySegmentById(tCitySegment.getId());
        if (delcount == 1) {
            if (tCitySegmentOld.getIpStartI() < newIpStartI) {
                TCitySegment tTotalSegmentNew = new TCitySegment();
                BeanUtils.copyProperties(tCitySegment, tTotalSegmentNew, "id");
                tTotalSegmentNew.setIpEndI(newIpStartI - 1);
                tTotalSegmentNew.setIpEnd(NetUtil.longToIpv4(newIpStartI - 1));
                tTotalSegmentNew.setIpStart(tCitySegmentOld.getIpStart());
                tTotalSegmentNew.setIpStartI(tCitySegmentOld.getIpStartI());
                tTotalSegmentNew.setCreateTime(tCitySegmentOld.getCreateTime());
                tTotalSegmentNew.setCreateBy(tCitySegmentOld.getCreateBy());
                this.insertTCitySegment(tTotalSegmentNew);
            }

            if (tCitySegmentOld.getIpEndI() > newIpEndI) {
                TCitySegment tTotalSegmentNew = new TCitySegment();
                BeanUtils.copyProperties(tCitySegment, tTotalSegmentNew, "id");
                tTotalSegmentNew.setIpStartI(newIpEndI + 1);
                tTotalSegmentNew.setIpStart(NetUtil.longToIpv4(newIpEndI + 1));
                tTotalSegmentNew.setIpEndI(tCitySegmentOld.getIpEndI());
                tTotalSegmentNew.setIpEnd(tCitySegmentOld.getIpEnd());
                tTotalSegmentNew.setCreateTime(tCitySegmentOld.getCreateTime());
                tTotalSegmentNew.setCreateBy(tCitySegmentOld.getCreateBy());
                this.insertTCitySegment(tTotalSegmentNew);
            }
        }
        tCitySegmentOld.setUpdateTime(DateUtils.getNowDate());
        tCitySegmentOld.setId(null);
        tCitySegmentOld.setIpStartI(newIpStartI);
        tCitySegmentOld.setIpStart(tCitySegment.getIpStart());
        tCitySegmentOld.setIpEndI(newIpEndI);
        tCitySegmentOld.setIpEnd(tCitySegment.getIpEnd());
        BeanUtil.copyProperties(tCitySegment, tCitySegmentOld, "id", "createBy", "createTime", "updateBy", "updateTime",
                "ipStart", "ipStartI", "ipEnd", "ipEndI");

        return this.insertTCitySegment(tCitySegmentOld);
    }

    /**
     * 批量删除城市ip段
     *
     * @param ids 需要删除的城市ip段主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTCitySegmentByIds(Long[] ids) {
        return tCitySegmentMapper.deleteTCitySegmentByIds(ids);
    }

    /**
     * 删除城市ip段信息
     *
     * @param id 城市ip段主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTCitySegmentById(Long id) {
        return tCitySegmentMapper.deleteTCitySegmentById(id);
    }

    /**
     * 导入全量地址段管理数据
     *
     * @param tCitySegmentList 地市地址段管理列表
     * @return 结果
     */
    @Override
    @Transactional
    public synchronized int importCitySegment(List<TCitySegment> tCitySegmentList) {

        if (CollUtil.isEmpty(tCitySegmentList)) {
            throw new ServiceException("导入地市地址段数据不能为空！");
        }

        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long deptid = user.getDeptId();
        Long pdeptid = deptid;
        if (deptid != 100) {
            pdeptid = user.getDept().getParentId();
        }
        String city_e = CacheKitUtil.ip_dept.get(String.valueOf(pdeptid));
        String city_zh = Caches.getDeptName(String.valueOf(pdeptid));

        for (int i = 0; i < tCitySegmentList.size(); i++) {
            TCitySegment tcs = tCitySegmentList.get(i);
            try {

                tcs.setIpStart(tcs.getIpStart().trim());
                if (tcs.getIpStart().contains("/")) {
                    String[] ips = tcs.getIpStart().split("/");
                    tcs.setIpStart(ips[0].trim());
                    tcs.setIpStartI(NetUtil.ipv4ToLong(ips[0].trim()));
                    tcs.setIpEndI(Ipv4Util.getEndIpLong(ips[0].trim(), Convert.toInt(ips[1])));
                    tcs.setIpEnd(NetUtil.longToIpv4(tcs.getIpEndI()));
                    tcs.setIpEndI(NetUtil.ipv4ToLong(tcs.getIpEnd()));
                } else {
                    tcs.setIpEnd(tcs.getIpEnd().trim());
                    tcs.setIpStartI(NetUtil.ipv4ToLong(tcs.getIpStart().trim()));
                    tcs.setIpEndI(NetUtil.ipv4ToLong(tcs.getIpEnd().trim()));
                }

            } catch (Exception e) {
                log.error(e.getMessage());
                throw new ServiceException(
                        String.format("第%d行数据异常，起始地址为：%s,异常原因：%s", i + 2, tcs.getIpStart(), "数据格式不正确"));
            }
            if (StringUtils.isBlank(tcs.getIpCity())) {
                throw new ServiceException(
                        String.format("第%d行数据异常，起始地址为：%s,异常原因：%s", i + 2, tcs.getIpStart(), "地市不能为空"));
            }
            if (deptid != 100) {
                if (!tcs.getIpCity().equals(city_zh)) {
                    throw new ServiceException(String.format("第%d行数据异常，起始地址为：%s,异常原因：%s", i + 2, tcs.getIpStart(),
                            "只能上传'" + city_zh + "'市数据"));
                }
            }

            String iptype = StrUtil.isNotBlank(tcs.getIpType()) ? tcs.getIpType() : "ip_area";
//            if (!UserUtils.isRole(iptype)) {
//                throw new ServiceException(String.format("第%d行数据异常，起始地址为：%s,异常原因：%s", i + 2, tcs.getIpStart(),
//                        "没有网络类型：" + tcs.getIpType() + " 的权限"));
//            }
            if (deptid == 100) {
                city_e = CacheKitUtil.ip_city.getKey(tcs.getIpCity());
            }


            List<?> startList = Db.find(
                    "select distinct id from t_total_segment where ip_start_i <= ? and ip_end_i >= ? and ip_type = ? and ip_city = ?",
                    tcs.getIpStartI(), tcs.getIpStartI(), iptype, city_e);

            List<?> endList = Db.find(
                    "select distinct id from t_total_segment where ip_start_i <= ? and ip_end_i >= ? and ip_type = ? and ip_city = ?",
                    tcs.getIpEndI(), tcs.getIpEndI(), iptype, city_e);

            if (CollUtil.isEmpty(startList) || CollUtil.isEmpty(endList)) {
                throw new ServiceException(
                        String.format("第%d行数据异常，起始地址为：%s,异常原因：%s", i + 2, tcs.getIpStart(), "起始地址或终止地址在省地址中未分配"));
            }

            List<Record> repeatList1 = Db.find(
                    "select * from t_city_segment where (( ( ip_start_i between ? and ? ) or ( ip_end_i between ? and ? ) ) or "
                            + " ( ip_start_i <=? and ip_end_i >= ? )) and ip_city = ? ",
                    tcs.getIpStartI(), tcs.getIpEndI(), tcs.getIpStartI(), tcs.getIpEndI(), tcs.getIpStartI(),
                    tcs.getIpEndI(), city_e);
            if (repeatList1.size() > 0) {
                throw new ServiceException(
                        String.format("第%d行数据异常，起始地址为：%s,异常原因：%s", i + 2, tcs.getIpStart(), "该地址段部分已导入"));
            }


            tcs.setIpCity(city_e);
            if (StringUtils.isBlank(tcs.getIpType())) {
                tcs.setIpType("on");
            }
            tcs.setIpType(iptype);
            tcs.setIpUseType(ip_use_type.getKey(tcs.getIpUseType()));
            if (StrUtil.isEmpty(tcs.getIpStatus())) {
                tcs.setIpStatus("on");
            } else {
                tcs.setIpStatus(ip_status.getKey(tcs.getIpStatus()));
            }
            tcs.setCreateTime(new Date());
            tcs.setCreateBy(user.getUserName());
        }


        for (int i = 0; i < tCitySegmentList.size(); i++) {
            TCitySegment tcs1 = tCitySegmentList.get(i);
            for (int j = i + 1; j < tCitySegmentList.size(); j++) {
                TCitySegment tcs2 = tCitySegmentList.get(j);
                if (tcs1.getIpStartI() > tcs2.getIpStartI() && tcs1.getIpStartI() < tcs2.getIpEndI()) {
                    throw new ServiceException(String.format("第%d行数据异常，起始地址为：%s,异常原因：%s", i + 2, tcs1.getIpStart(),
                            "起始地址和第" + (j + 2) + "行有重复"));
                }
                if (tcs1.getIpEndI() < tcs2.getIpEndI() && tcs1.getIpEndI() > tcs2.getIpStartI()) {
                    throw new ServiceException(String.format("第%d行数据异常，终止地址为：%s,异常原因：%s", i + 2, tcs1.getIpEnd(),
                            "终止地址和第" + (j + 2) + "行有重复"));
                }
                if (tcs1.getIpStartI() <= tcs2.getIpStartI() && tcs1.getIpEndI() >= tcs2.getIpEndI()) {
                    throw new ServiceException(String.format("第%d行数据异常，起始地址为：%s,异常原因：%s", i + 2, tcs1.getIpStart(),
                            "起始地址和第" + (j + 2) + "行有重复"));
                }
            }
        }


        for (int i = 0; i < tCitySegmentList.size(); i++) {
            try {
                tCitySegmentMapper.insertTCitySegment(tCitySegmentList.get(i));
            } catch (Exception e) {
                log.error("", e);
                throw new ServiceException(String.format("第%d行数据异常，起始地址为：%s,异常原因：%s", i + 2,
                        tCitySegmentList.get(i).getIpStart(), "数据无法插入数据库，请联系管理员"));
            }
        }

        return tCitySegmentList.size();
    }

    /**
     * 导入全量地址段管理数据--导入修改
     *
     * @param tCitySegmentList 地市地址段管理列表
     * @return 结果
     */
    @Override
//    @Transactional
    public synchronized int importCitySegmentEdit(List<TCitySegment> tCitySegmentList) {

        if (CollUtil.isEmpty(tCitySegmentList)) {
            throw new ServiceException("导入地市地址段数据不能为空！");
        }

        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long deptid = user.getDeptId();
        Long pdeptid = deptid;
        if (deptid != 100) {
            pdeptid = user.getDept().getParentId();
        }
        String city_e = CacheKitUtil.ip_dept.get(String.valueOf(pdeptid));
        String city_zh = Caches.getDeptName(String.valueOf(pdeptid));

        for (int i = 0; i < tCitySegmentList.size(); i++) {
            TCitySegment tcs = tCitySegmentList.get(i);
            try {

                tcs.setIpStart(tcs.getIpStart().trim());
                if (tcs.getIpStart().contains("/")) {
                    String[] ips = tcs.getIpStart().split("/");
                    tcs.setIpStart(ips[0].trim());
                    tcs.setIpStartI(NetUtil.ipv4ToLong(ips[0].trim()));
                    tcs.setIpEndI(Ipv4Util.getEndIpLong(ips[0].trim(), Convert.toInt(ips[1])));
                    tcs.setIpEnd(NetUtil.longToIpv4(tcs.getIpEndI()));
                    tcs.setIpEndI(NetUtil.ipv4ToLong(tcs.getIpEnd()));
                } else {
                    tcs.setIpEnd(tcs.getIpEnd().trim());
                    tcs.setIpStartI(NetUtil.ipv4ToLong(tcs.getIpStart().trim()));
                    tcs.setIpEndI(NetUtil.ipv4ToLong(tcs.getIpEnd().trim()));
                }

            } catch (Exception e) {
                log.error(e.getMessage());
                throw new ServiceException(
                        String.format("第%d行数据异常，起始地址为：%s,异常原因：%s", i + 2, tcs.getIpStart(), "数据格式不正确"));
            }
            if (StringUtils.isBlank(tcs.getIpCity())) {
                throw new ServiceException(
                        String.format("第%d行数据异常，起始地址为：%s,异常原因：%s", i + 2, tcs.getIpStart(), "地市不能为空"));
            }
            if (deptid != 100) {
                if (!tcs.getIpCity().equals(city_zh)) {
                    throw new ServiceException(String.format("第%d行数据异常，起始地址为：%s,异常原因：%s", i + 2, tcs.getIpStart(),
                            "只能上传'" + city_zh + "'市数据"));
                }
            }

            String iptype = StrUtil.isNotBlank(tcs.getIpType()) ? tcs.getIpType() : "ip_area";
            if (deptid == 100) {
                city_e = CacheKitUtil.ip_city.getKey(tcs.getIpCity());
            }

            tcs.setCreateTime(new Date());
            tcs.setCreateBy(user.getUserName());
            //////////////////////////////////////////////////
            CitySegment citySegment = csdao.findFirst("select * from t_city_segment \n" +
                            " where ip_start_i <= ? and ip_end_i >= ?  and ip_city = ? ",
                    tcs.getIpStartI(), tcs.getIpEndI(), city_e);
//            Record citySegment = Db.findFirst(
//                    "select * from t_city_segment \n" +
//                            " where ip_start_i <= ? and ip_end_i >= ?  and ip_city = ? ",
//                    tcs.getIpStartI(), tcs.getIpEndI(), city_e);

            if (null == citySegment) {
                throw new ServiceException(String.format("第%d行数据异常，终止地址为：%s,异常原因：%s", i + 2, tcs.getIpEnd(),
                        "表中无该地址段数据"));
            }
            //举例说明：原地址段：10.1.2.0 - 10.1.2.255  未使用 。。。。。。
            //  根据excel表格中导入的地址段信息修改10.1.2.10 - 10.1.2.20  为 地址池 。。。。。。
            //其他剩下的地址段保持原来信息不变。
            //修改后的结果：10.1.2.0 - 10.1.2.9  未使用 。。。。。。
            //  10.1.2.10 - 10.1.2.20  地址池 。。。。。。
            //  10.1.2.21 - 10.1.2.255 未使用 。。。。。。

            TCitySegment newTCitySegment = new TCitySegment();
            TCitySegment newTCitySegmentUpBegin = new TCitySegment();
            TCitySegment newTCitySegmentUpEnd = new TCitySegment();
            //相等
            //b=? && e=?
            if (NumberUtil.compare(citySegment.getLong("ip_start_i"), tcs.getIpStartI()) == 0 &&
                    NumberUtil.compare(citySegment.getLong("ip_end_i"), tcs.getIpEndI()) == 0) {
                BeanUtils.copyProperties(citySegment, newTCitySegment);
//                newTCitySegment.setIpUseType(ip_use_type.getKey(tcs.getIpUseType()));
                setTDcnCity(newTCitySegment, tcs);
                tCitySegmentMapper.updateTCitySegment(newTCitySegment);
            } else if (NumberUtil.compare(citySegment.getLong("ip_start_i"), tcs.getIpStartI()) == 0 &&
                    NumberUtil.compare(citySegment.getLong("ip_end_i"), tcs.getIpEndI()) == 1) {
                //b=? && e>?
                BeanUtils.copyProperties(citySegment, newTCitySegment);
                BeanUtils.copyProperties(citySegment, newTCitySegmentUpEnd);
                newTCitySegment.setIpEnd(tcs.getIpEnd());
                newTCitySegment.setIpEndI(tcs.getIpEndI());
//                newTCitySegment.setIpUseType(ip_use_type.getKey(tcs.getIpUseType()));
                setTDcnCity(newTCitySegment, tcs);
                tCitySegmentMapper.updateTCitySegment(newTCitySegment);

                newTCitySegmentUpEnd.setIpStartI(tcs.getIpEndI() + 1);
                newTCitySegmentUpEnd.setIpStart(NetUtil.longToIpv4(newTCitySegmentUpEnd.getIpStartI()));
                tCitySegmentMapper.insertTCitySegment(newTCitySegmentUpEnd);
            } else if (NumberUtil.compare(citySegment.getLong("ip_start_i"), tcs.getIpStartI()) == -1 &&
                    NumberUtil.compare(citySegment.getLong("ip_end_i"), tcs.getIpEndI()) == 0) {
                //b<? && e=?
                BeanUtils.copyProperties(citySegment, newTCitySegment);
                BeanUtils.copyProperties(citySegment, newTCitySegmentUpBegin);

                newTCitySegment.setIpStartI(tcs.getIpStartI());
                newTCitySegment.setIpStart(tcs.getIpStart());
//                newTCitySegment.setIpUseType(ip_use_type.getKey(tcs.getIpUseType()));
                setTDcnCity(newTCitySegment, tcs);
                tCitySegmentMapper.updateTCitySegment(newTCitySegment);

                newTCitySegmentUpBegin.setIpEndI(tcs.getIpStartI() - 1);
                newTCitySegmentUpBegin.setIpEnd(NetUtil.longToIpv4(newTCitySegmentUpBegin.getIpEndI()));
                tCitySegmentMapper.insertTCitySegment(newTCitySegmentUpBegin);
            } else if (NumberUtil.compare(citySegment.getLong("ip_start_i"), tcs.getIpStartI()) == -1 &&
                    NumberUtil.compare(citySegment.getLong("ip_end_i"), tcs.getIpEndI()) == 1) {
                //b<? && e>?
                BeanUtils.copyProperties(citySegment, newTCitySegment);
                BeanUtils.copyProperties(citySegment, newTCitySegmentUpEnd);
                BeanUtils.copyProperties(citySegment, newTCitySegmentUpBegin);

                newTCitySegment.setIpStartI(tcs.getIpStartI());
                newTCitySegment.setIpStart(tcs.getIpStart());
                newTCitySegment.setIpEnd(tcs.getIpEnd());
                newTCitySegment.setIpEndI(tcs.getIpEndI());
//                newTCitySegment.setIpUseType(ip_use_type.getKey(tcs.getIpUseType()));
                setTDcnCity(newTCitySegment, tcs);
                tCitySegmentMapper.updateTCitySegment(newTCitySegment);

                newTCitySegmentUpBegin.setIpEndI(tcs.getIpStartI() - 1);
                newTCitySegmentUpBegin.setIpEnd(NetUtil.longToIpv4(newTCitySegmentUpBegin.getIpEndI()));
                tCitySegmentMapper.insertTCitySegment(newTCitySegmentUpBegin);

                newTCitySegmentUpEnd.setIpStartI(tcs.getIpEndI() + 1);
                newTCitySegmentUpEnd.setIpStart(NetUtil.longToIpv4(newTCitySegmentUpEnd.getIpStartI()));
                tCitySegmentMapper.insertTCitySegment(newTCitySegmentUpEnd);
            }

        }
        return tCitySegmentList.size();
    }

    //地市不能修改
    private void setTDcnCity(TCitySegment dbTDcnCity, TCitySegment webTDcnCity) {
        dbTDcnCity.setIpUseType(ip_use_type.getKey(webTDcnCity.getIpUseType()));

        if (StrUtil.isNotEmpty(webTDcnCity.getIpUser())) {
            dbTDcnCity.setIpUser(webTDcnCity.getIpUser());
        }
        if (StrUtil.isNotEmpty(webTDcnCity.getIpManagement())) {
            dbTDcnCity.setIpManagement(webTDcnCity.getIpManagement());
        }
        if (StrUtil.isNotEmpty(webTDcnCity.getIpEquipment())) {
            dbTDcnCity.setIpEquipment(webTDcnCity.getIpEquipment());
        }
        if (StrUtil.isNotEmpty(webTDcnCity.getIpUsername())) {
            dbTDcnCity.setIpUsername(webTDcnCity.getIpUsername());
        }
        if (StrUtil.isNotEmpty(webTDcnCity.getPort())) {
            dbTDcnCity.setPort(webTDcnCity.getPort());
        }
        if (StrUtil.isNotEmpty(webTDcnCity.getIpGateway())) {
            dbTDcnCity.setIpGateway(webTDcnCity.getIpGateway());
        }
        if (StrUtil.isNotEmpty(webTDcnCity.getBusinessNumber())) {
            dbTDcnCity.setBusinessNumber(webTDcnCity.getBusinessNumber());
        }
        if (StrUtil.isNotEmpty(webTDcnCity.getRecordStatus())) {
            dbTDcnCity.setRecordStatus(CacheKitUtil.ip_record.get(webTDcnCity.getRecordStatus()));
        }
//        if(StrUtil.isNotEmpty(webTDcnCity.getBusinessNumber())){
//            dbTDcnCity.setBusinessNumber(webTDcnCity.getBusinessNumber());
//        }
        if (StrUtil.isNotEmpty(webTDcnCity.getRemark())) {
            dbTDcnCity.setRemark(webTDcnCity.getRemark());
        }
        if (StrUtil.isNotEmpty(webTDcnCity.getIpStatus())) {
            dbTDcnCity.setIpStatus(ip_status.getKey(webTDcnCity.getIpStatus()));
        }
    }

    public static void main(String[] args) {

        long a = NetUtil.ipv4ToLong("202.96.85.0");
        long b = NetUtil.ipv4ToLong("202.96.85.31");
        System.out.println(a);
        System.out.println(b);

    }

}
